package preorderlayer

import (
    "time"
    "errors"
	"strconv"
	"encoding/json"
	"dhfshop/models/consts"
	"dhfshop/models/preorder"
	"dhfshop/models/member"
	"dhfshop/models/im"
	"dhfshop/models/isv"
	"dhfshop/domain/im"
	"github.com/astaxie/beego"
)

// 扣减号源
func ReduceSource(srcTimeslot *preorder.Timeslots)(curNo int, err error) {
	beego.Debug("srcTimeslot.CurCount:", srcTimeslot.CurCount)
	beego.Debug("srcTimeslot.MaxCount:", srcTimeslot.MaxCount)
	if srcTimeslot.CurCount > srcTimeslot.MaxCount {
		err = errors.New(ErrTimeslotNoSuchSource.Error())
		return
	}
	srcTimeslot.CurCount++
	curNo = srcTimeslot.CurCount
	beego.Debug("curNo:", curNo)
	if err = preorder.UpdateTimeslotsById(srcTimeslot, "cur_count"); err != nil {
		return
	}
	return
}

// 基于模板消息通知按时赴约
func TimeoutRemindReserve(recallMsg string) (err error) {
	type RecallReserveMsg struct {
		PreOrderId   int64 `json:"pre_order_id"`
	}
	var msg RecallReserveMsg
	if err = json.Unmarshal([]byte(recallMsg), &msg); err != nil {
		return err
	}
	preOrderIdStr := strconv.FormatInt(msg.PreOrderId, 10)
	preOrder, err := preorder.GetPreOrderById(msg.PreOrderId)
	if err != nil {
	    beego.Debug("GetPreOrderById:", err.Error())
	    return
	}
	if preOrder.SourceAt.Unix() - time.Now().UTC().Unix() > 24*3600 {
	    beego.Debug("preOrder source_at is not correct")
	}
	members, err := member.GetMemberById(preOrder.MemberId)
	if err != nil {
	    beego.Debug("GetMemberById:", err.Error())
		return
	}
	custAccount, err := isv.GetCustAccountByAppId(members.AppId)
	if err != nil {
		beego.Debug("GetCustAccountByAppId:", err.Error())
		return
	}
	templateId, err := imlayer.GetTemplateId(custAccount.PartnerId,members.AppId,"AT0240")
	if err != nil {
		beego.Debug("GetTemplateId:", err.Error())
		return
	}
	formId, err := im.GetFormIdByOpenId(members.OpenID,"yuyue",preOrderIdStr)
	if err != nil {
		beego.Debug("GetFormIdByOpenId:", err.Error())
		return
	}			    
	page := ""
	sortNumber := strconv.Itoa(preOrder.OrderSeq)
	sourceTime := preOrder.SourceAt.Format(consts.DATE_FORMAT)
	err = imlayer.ReserveArriveTempMsg(custAccount.AccessToken,page,members.OpenID,templateId,
	                           formId,preOrder.ResItem.Name,sortNumber,sourceTime)
	if err != nil {
		beego.Debug("ReserveArriveTempMsg:", err.Error())
	}
	return
}


